#include <QFile>
#include "qlogger.hpp"

int QLoggerEngine::elapsed ()
{
    return handle().startTime.elapsed();
}

bool QLoggerEngine::isEventAccepted (QLoggerAppender *appender, QLoggerEvent &event)
{
    if (!(appender->level() & event.level))
       return false;
    return true;
}

void QLoggerEngine::logEvent (const QLogger &logger, QLoggerLevel level, const QString &message, const char *file, int line)
{
    QLoggerEvent event;
    event.dateTime = QDateTime::currentDateTime();
    event.logger = &logger;
    event.level = level;
    event.message = &message;
    event.file = file;
    event.line = line;

    foreach (QLoggerAppender *appender, handle().appenders) {
        if (isEventAccepted(appender, event) == true) {
            appender->write(event);
        }
    }
}

QLogger & QLoggerEngine::logger (const QString &moduleName)
{
    QLogger *logger;
    logger = handle().loggers[moduleName];
    if (logger == NULL) {
        logger = new QLogger(moduleName);
        handle().loggers[moduleName] = logger;
    }
    return (*logger);
}

const char * QLoggerEngine::levelName (QLoggerLevel level)
{
    switch (level) {
        case LevelDebug:
            return "Debug";
        case LevelInfo:
            return "Info";
        case LevelWarn:
            return "Warn";
        case LevelError:
            return "Error";
        case LevelCritical:
            return "Critical";
        case LevelFatal:
            return "Fatal";
        case LevelException:
            return "Exception";
        default:
            return "Unknown";
    }
}

void QLoggerEngine::configureConsoleAppender (int level, FILE *stream, const QString &format)
{
    QLoggerConsoleAppender *appender = new QLoggerConsoleAppender(level, stream, format);
    handle().appenders << appender;
}

void QLoggerEngine::configureFileAppender (int level, const QString &filename, const QString &format, bool truncate, bool backup)
{
    if (backup == true)
        QFile(filename).rename(filename + QDateTime::currentDateTime().toString("yyyy.MM.dd-hh.mm.ss") + ".bak");

    if (truncate == true)
        QFile(filename).remove();

    QLoggerFileAppender *appender = new QLoggerFileAppender(level, filename, format);
    handle().appenders << appender;
}

QLoggerEngine::~QLoggerEngine ()
{
    while (!appenders.isEmpty())
        delete appenders.takeLast();
    foreach (QLogger *logger, loggers) {
        delete logger;
    }
}
